#include "U2DynLibManager.h"

#include "U2DynLib.h"



U2EG_NAMESPACE_USING


//-----------------------------------------------------------------------
template<> U2DynLibManager* U2Singleton<U2DynLibManager>::s_pSingleton = 0;

U2DynLibManager* U2DynLibManager::getSingletonPtr(void)
{
    return s_pSingleton;
}

U2DynLibManager& U2DynLibManager::getSingleton(void)
{  
    assert( s_pSingleton );
    return ( *s_pSingleton );  
}

U2DynLibManager::U2DynLibManager()
{
}

U2DynLibManager::~U2DynLibManager(void)
{
    // Unload & delete resources in turn
    for ( U2DynLibList::iterator it = m_libList.begin(); it != m_libList.end(); ++it )
    {
        it->second->unload();
        U2_DELETE it->second;
    }

    // Empty the list
    m_libList.clear();
}

U2DynLib* U2DynLibManager::load(const U2String& filename)
{
	U2DynLibList::iterator i = m_libList.find(filename);
	if (i != m_libList.end())
	{
		return i->second;
	}
	else
	{
		U2DynLib* pLib = U2_NEW U2DynLib(filename);
		pLib->load();        
		m_libList[filename] = pLib;
		return pLib;
	}
}

void U2DynLibManager::unload(U2DynLib* pLib)
{
	U2DynLibList::iterator i = m_libList.find(pLib->getName());
	if (i != m_libList.end())
	{
		m_libList.erase(i);
	}
	pLib->unload();
	U2_DELETE(pLib);
}